package com.xju.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.xju.entity.College;
import com.xju.entity.Class;

import static com.xju.util.DBUtil.getConnection;

public class ClassDaoImpl implements ClassDao {


    @Override
    public List<Class> findClassesByMajorId(Integer majorId) {
        // 1. 定义SQL查询语句（根据major_id查询班级）
        String sql = "SELECT class_id, class_name FROM class WHERE major_id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 3. 设置参数（majorId）
            stmt.setInt(1, majorId);

            // 4. 执行查询
            ResultSet rs = stmt.executeQuery();

            // 5. 遍历结果集，封装成Class对象列表
            List<Class> classes = new ArrayList<>();
            while (rs.next()) {
                Class cls = new Class();
                cls.setClassId(rs.getInt("class_id"));       // 设置班级ID
                cls.setClassName(rs.getString("class_name")); // 设置班级名称
                classes.add(cls);
            }

            // 6. 返回查询结果
            return classes;

        } catch (SQLException e) {
            e.printStackTrace();  // 打印异常信息
            return Collections.emptyList();  // 发生异常时返回空列表，避免返回null
        }
    }
    @Override
    public List<Class> findClassesByName(String name) {
        // 使用LIKE进行模糊查询（前后加%表示包含匹配）
        String sql = "SELECT class_id, class_name FROM class WHERE class_name LIKE ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置查询参数（添加通配符%）
            stmt.setString(1, "%" + name + "%");

            ResultSet rs = stmt.executeQuery();
            List<Class> classes = new ArrayList<>();

            while (rs.next()) {
                Class cls = new Class();
                cls.setClassId(rs.getInt("class_id"));
                cls.setClassName(rs.getString("class_name"));
                classes.add(cls);
            }

            return classes;

        } catch (SQLException e) {
            e.printStackTrace();
            return Collections.emptyList(); // 返回空列表而非null
        }
    }
}